﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace WpfDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContextChanged += OnMainWindowDataContextChanged;
            Loaded += OnMainWindowLoaded;
        }

        private void OnMainWindowLoaded(object sender, RoutedEventArgs e)
        {
            var viewModel = (WpfDemoViewModel) DataContext;
            viewModel.PropertyChanged += OnViewModelPropertyChanged;
        }

        private void OnMainWindowDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var viewModel = (WpfDemoViewModel)e.NewValue;
            if (viewModel == null) return;
            viewModel.PropertyChanged += OnViewModelPropertyChanged;
        }

        private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName != nameof(WpfDemoViewModel.CurrentDataTime)) return;
            
            var storyBoard = new Storyboard(){ AutoReverse = true};
            var animation = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(500)));
            Storyboard.SetTarget(animation, PART_StoryBoardInCodeTextBlock);
            Storyboard.SetTargetProperty(animation, new PropertyPath(nameof(TextBlock.Opacity)));
            storyBoard.Children.Add(animation);
            PART_StoryBoardInCodeTextBlock.BeginStoryboard(storyBoard);
        }
    }
}